package com.nft.service.school.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nft.constant.response.ResponseConstants;
import com.nft.paging.Paginator;
import com.nft.po.NftResponse;
import com.nft.service.school.entity.SysDeptEntity;
import com.nft.service.school.entity.SysUserEntity;
import com.nft.service.school.mapper.SysDeptMapper;
import com.nft.service.school.mapper.SysUserMapper;
import com.nft.service.school.req.SysDeptReq;
import com.nft.service.school.req.SysUserReq;
import com.nft.service.school.resp.SysDeptResp;
import com.nft.service.school.service.SysDeptService;
import com.nft.utils.query.QueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDeptEntity> implements SysDeptService {
    @Resource
    private StringRedisTemplate myRedisTemplate;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public NftResponse<Paginator<SysDeptResp>> getSchoolList(SysDeptReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        QueryWrapper<SysUserEntity> wrapperQueryUser = new QueryWrapper<>();
        wrapperQueryUser.eq(QueryUtil.camelToUnderline("phonenumber"), query.getPhone());
        wrapperQueryUser.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperQueryUser.eq(QueryUtil.camelToUnderline("status"), "0");
        List<SysUserEntity> userList = sysUserMapper.selectList(wrapperQueryUser);
        List<Long> deptIds = new ArrayList<>();
        for (SysUserEntity obj:userList) {
            deptIds.add(obj.getDeptId());
        }
        Paginator<SysDeptResp> paginator = new Paginator<SysDeptResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<SysDeptEntity> wrapperQuery = new QueryWrapper<>();
        wrapperQuery.ne(QueryUtil.camelToUnderline("parentId"), "0");
        wrapperQuery.eq(QueryUtil.camelToUnderline("status"), "0");
        wrapperQuery.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperQuery.orderByAsc("order_num");
        Page<SysDeptEntity> resultPage = this.baseMapper.selectPage(new Page<>(query.getPageNo(),query.getPageSize()),wrapperQuery);
        List<SysDeptResp> pageResult = BeanUtil.copyToList(resultPage.getRecords(), SysDeptResp.class);
        for (SysDeptResp obj:pageResult) {
            if (null!=deptIds&&deptIds.size()>0&&deptIds.contains(obj.getDeptId())) {
                obj.setIsMe(true);
            }else {
                obj.setIsMe(false);
            }
        }
        paginator.setPageNo(resultPage.getCurrent());
        paginator.setPageSize(resultPage.getSize());
        paginator.setTotalDataNum(resultPage.getTotal());
        paginator.setPageData(pageResult);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<List<SysDeptResp>> getSchoolAllList(SysDeptReq query) {
        List<SysDeptEntity> list = new ArrayList<>();
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("SCHOOL:DEPT");
        if (mapValue.isEmpty()) {
            QueryWrapper<SysDeptEntity> wrapperQuery = new QueryWrapper<>();
            wrapperQuery.ne(QueryUtil.camelToUnderline("parentId"), "0");
            wrapperQuery.eq(QueryUtil.camelToUnderline("status"), "0");
            wrapperQuery.eq(QueryUtil.camelToUnderline("delFlag"),"0");
            wrapperQuery.orderByAsc("order_num");
            list = this.baseMapper.selectList(wrapperQuery);
            Map<String, String> schoolDMap = new HashMap<>();
            for (SysDeptEntity obj:list) {
                schoolDMap.put(obj.getDeptId()+"", JSON.toJSONString(obj));
            }
            myRedisTemplate.opsForHash().putAll("SCHOOL:DEPT", schoolDMap);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                SysDeptEntity entity = JSON.parseObject(entry.getValue().toString(), SysDeptEntity.class);
                list.add(entity);
            }
        }
        List<SysDeptResp> result = BeanUtil.copyToList(list, SysDeptResp.class);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", result);
    }

    @Override
    public NftResponse<SysDeptResp> getSchoolInfoById(Long deptId) {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("SCHOOL:DEPT");
        Object deptValue = mapValue.get(deptId+"");
        SysDeptResp schoolResp = null;
        if (null!=deptValue) {
            SysDeptEntity entity = JSON.parseObject(deptValue.toString(), SysDeptEntity.class);
            schoolResp = BeanUtil.copyProperties(entity, SysDeptResp.class);
        }else {
            QueryWrapper<SysDeptEntity> wrapperQuery = new QueryWrapper<>();
            wrapperQuery.ne(QueryUtil.camelToUnderline("parentId"), "0");
            wrapperQuery.eq(QueryUtil.camelToUnderline("status"), "0");
            wrapperQuery.eq(QueryUtil.camelToUnderline("delFlag"),"0");
            wrapperQuery.orderByAsc("order_num");
            List<SysDeptEntity> list = this.baseMapper.selectList(wrapperQuery);
            Map<String, String> schoolDMap = new HashMap<>();
            for (SysDeptEntity obj:list) {
                schoolDMap.put(obj.getDeptId()+"", JSON.toJSONString(obj));
                if (obj.getDeptId()==deptId) {
                    schoolResp = BeanUtil.copyProperties(obj, SysDeptResp.class);
                }
            }
            myRedisTemplate.opsForHash().putAll("SCHOOL:DEPT", schoolDMap);
        }
        if (schoolResp == null) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "查无此学校", null);
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", schoolResp);
    }

    @Override
    public NftResponse<List<SysDeptResp>> getSchoolListByPhone(SysUserReq query) {
        QueryWrapper<SysUserEntity> wrapperQueryUser = new QueryWrapper<>();
        wrapperQueryUser.eq(QueryUtil.camelToUnderline("phonenumber"), query.getPhone());
        wrapperQueryUser.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperQueryUser.eq(QueryUtil.camelToUnderline("status"), "0");
        List<SysUserEntity> userList = sysUserMapper.selectList(wrapperQueryUser);
        List<Long> deptIds = new ArrayList<>();
        for (SysUserEntity obj:userList) {
            deptIds.add(obj.getDeptId());
        }
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("SCHOOL:DEPT");
        List<SysDeptEntity> list = new ArrayList<>();
        if (mapValue.isEmpty()) {
            QueryWrapper<SysDeptEntity> wrapperQuery = new QueryWrapper<>();
            wrapperQuery.ne(QueryUtil.camelToUnderline("parentId"), "0");
            wrapperQuery.eq(QueryUtil.camelToUnderline("status"), "0");
            wrapperQuery.eq(QueryUtil.camelToUnderline("delFlag"),"0");
            wrapperQuery.orderByAsc("order_num");
            list = this.baseMapper.selectList(wrapperQuery);
            Map<String, String> schoolDMap = new HashMap<>();
            for (SysDeptEntity obj:list) {
                schoolDMap.put(obj.getDeptId()+"", JSON.toJSONString(obj));
            }
            myRedisTemplate.opsForHash().putAll("SCHOOL:DEPT", schoolDMap);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                SysDeptEntity entity = JSON.parseObject(entry.getValue().toString(), SysDeptEntity.class);
                list.add(entity);
            }
        }
        List<SysDeptResp> result = BeanUtil.copyToList(list, SysDeptResp.class);
        for (SysDeptResp obj:result) {
            if (deptIds.contains(obj.getDeptId())) {
                obj.setIsMe(true);
            }else {
                obj.setIsMe(false);
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", result);
    }
}
